package com.zero.zeroframe.popup

import android.Manifest
import android.app.Activity
import android.os.Build
import android.view.View
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.UtilsTransActivity
import com.lxj.androidktx.core.toast
import com.zero.zeroframe.R
import com.zero.zeroframe.databinding.PopupImgBinding
import com.zero.zeroframe.utils.ImagePickerUtil
import com.zero.zeroframe.v.BasePopup
import kotlin.math.max

/**
 * 图片选择器
 *
 * @param isCrop 是否开启裁剪，默认false
 * @param isCompress 是否使用Luban压缩，默认是true
 * @param maxNum 图库选择最大数量
 */
class ImgPopup(activity: Activity,val isCrop: Boolean = false, val isCompress: Boolean = true,
               val maxNum: Int = 1, val multiListener: ((List<String>)->Unit)): BasePopup<PopupImgBinding>(activity, R.layout.popup_img) {

    override fun PopupImgBinding.initView() {
        setOutSideDismiss(false)
        setBackPressEnable(false)
        photograph.setOnClickListener {
            ImagePickerUtil.startCamera(context,isCrop = isCrop, isCompress =  isCompress) {
                multiListener.invoke(it)
            }
            dismiss()
        }
        album.setOnClickListener {
            ImagePickerUtil.startPicker(context,isCrop = isCrop, isCompress =  isCompress, maxNum = maxNum) {
                multiListener.invoke(it)
            }
            dismiss()
        }
        btnCancel.setOnClickListener { dismiss() }
    }

    override fun bindView(contentView: View) {
        mBinding = PopupImgBinding.bind(contentView)
    }

    override fun show() {
        val permissions = mutableListOf(
            Manifest.permission.CAMERA)
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        } else {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
            permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
        }
        val requestList = permissions.toTypedArray()
        PermissionUtils
            .permission(*requestList)
            .rationale(object : PermissionUtils.OnRationaleListener{
                override fun rationale(
                    activity: UtilsTransActivity,
                    shouldRequest: PermissionUtils.OnRationaleListener.ShouldRequest
                ) {
                    toast("rationale")
                }
            })
            .callback(object : PermissionUtils.SimpleCallback {
                override fun onGranted() {
                    showPopupWindow()
                }
                override fun onDenied() {
                    toast("权限被拒绝，无法使用")
                }
            })
            .request()
    }
}